//
//  HomePageWebVC.m
//  Futures
//
//  Created by Jone on 2017/9/26.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HomePageWebVC.h"
#import <Social/Social.h>
#import <WebKit/WebKit.h>
@interface HomePageWebVC ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIActionSheetDelegate>
{
    NSString * state;//根据分享开关设置分享内容
}
@property(strong,nonatomic)NSDictionary     *mHomePageDic;
@property(strong,nonatomic)WKWebView        *mWebView;
@property(strong,nonatomic)NSString         *mCurrent_Url;
@property(strong,nonatomic)NSDictionary     *mDictionary;


@property(strong,nonatomic)UIView           *mBottomView;
@property(strong,nonatomic)UIView           *mPopupView;
@property(strong,nonatomic)UIButton         *mOneBtn;
@property(strong,nonatomic)UIButton         *mTwoBtn;
@property(strong,nonatomic)UIButton         *mThrBtn;
@property(strong,nonatomic)UILabel          *mLineOne;
@property(strong,nonatomic)UILabel          *mLineTwo;

@property(strong,nonatomic)NSString         *mWebUrlStr;
@property(strong,nonatomic)UIImageView      *mWebImage;
@property(strong,nonatomic)NSArray          *mUrlArray;


@end

@implementation HomePageWebVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];

    self.navigationController.navigationBarHidden = YES;
    NSLog(@"urlstr ==  %@",self.LinkStr);
    [self createView];
}

#pragma mark 主视图
- (void)createView{
    
    
    
    UIView *aView = [[UIView alloc]initWithFrame:RectMake(0, 0, SCREEN_WIDTH, 20)];
    aView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:aView];
    self.mWebView = [[WKWebView alloc]initWithFrame:RectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.mWebView.backgroundColor = BackgroundColor;
    self.mWebView.userInteractionEnabled = YES;
    self.mWebView.scrollView.bounces = NO;

    
    self.mWebView.UIDelegate = self;
    self.mWebView.navigationDelegate = self;
    self.mWebView.scrollView.showsVerticalScrollIndicator = NO;
    NSURL* url = [NSURL URLWithString:self.LinkStr];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [self.mWebView loadRequest:request];
    
    [self.view addSubview:self.mWebView];
    self.mBottomView = [[UIView alloc]init];
    self.mBottomView.backgroundColor = HWColor(221, 52, 52);
    [self.view addSubview:self.mBottomView];
    self.mPopupView = [[UIView alloc]init];
    self.mPopupView.hidden = YES;
    self.mPopupView.backgroundColor = HWColor(221, 52, 52);
    self.mPopupView.userInteractionEnabled = YES;
    [self.mWebView addSubview:self.mPopupView];
    self.mOneBtn = [[UIButton alloc]init];
    self.mOneBtn.backgroundColor = [UIColor clearColor];
    [self.mOneBtn addTarget:self action:@selector(OneBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mOneBtn setTitle:@"分享" forState:UIControlStateNormal];
    [self.mOneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.mPopupView addSubview:self.mOneBtn];
    self.mTwoBtn = [[UIButton alloc]init];
    self.mTwoBtn.backgroundColor = [UIColor clearColor];
    [self.mTwoBtn setTitle:@"消息" forState:UIControlStateNormal];
    [self.mTwoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.mTwoBtn addTarget:self action:@selector(TwoBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mPopupView addSubview:self.mTwoBtn];
    self.mThrBtn = [[UIButton alloc]init];
    self.mThrBtn.backgroundColor = [UIColor clearColor];
    [self.mThrBtn setTitle:@"清除缓存" forState:UIControlStateNormal];
    [self.mThrBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.mThrBtn addTarget:self action:@selector(ThrBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mPopupView addSubview:self.mThrBtn];
    self.mLineOne = [[UILabel alloc]init];
    self.mLineOne.backgroundColor = [UIColor whiteColor];
    [self.mPopupView addSubview:self.mLineOne];
    self.mLineTwo = [[UILabel alloc]init];
    self.mLineTwo.backgroundColor = [UIColor whiteColor];
    [self.mPopupView addSubview:self.mLineTwo];
    
    WS(ws);
    [self.mBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.mWebView.mas_bottom);
        make.centerX.equalTo(ws.view.mas_centerX);
        make.size.mas_offset(CGSizeMake(SCREEN_WIDTH, 44));
    }];
    [self.mPopupView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(ws.mWebView.mas_right).with.offset(-5);
        make.bottom.equalTo(ws.mBottomView.mas_top).with.offset(-5);
        make.size.mas_offset(CGSizeMake(100, 110));
    }];
    [self.mOneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.mPopupView.mas_centerX);
        make.top.equalTo(ws.mPopupView.mas_top);
        make.size.mas_offset(CGSizeMake(100, 35));
    }];
    [self.mTwoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.mPopupView.mas_centerX);
        make.centerY.equalTo(ws.mPopupView.mas_centerY);
        make.size.mas_offset(CGSizeMake(100, 35));
    }];
    [self.mThrBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.mPopupView.mas_centerX);
        make.bottom.equalTo(ws.mPopupView.mas_bottom);
        make.size.mas_offset(CGSizeMake(100, 35));
    }];
    [self.mLineOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.mPopupView.mas_centerX);
        make.top.equalTo(ws.mOneBtn.mas_bottom);
        make.size.mas_offset(CGSizeMake(100, 1));
    }];
    [self.mLineTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.mPopupView.mas_centerX);
        make.top.equalTo(ws.mTwoBtn.mas_bottom);
        make.size.mas_offset(CGSizeMake(100, 1));
    }];
    
    NSArray *imageArr = @[@"shouye1",@"houtui1",@"jianjin1",@"shuaxins",@"zhucaidang1"];
    for (int i = 0; i<5; i++) {
        UIButton * aBtn = [[UIButton alloc] initWithFrame:CGRectMake(25+((SCREEN_WIDTH-30*6)/5+30)*i, 2, 40 ,40 )];
        aBtn.tag = i;
        [aBtn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [aBtn addTarget:self action:@selector(BottomAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.mBottomView addSubview:aBtn];
    }
}

- (void)BottomAction:(UIButton *)sender
{
    if (sender.tag == 0) {
        self.mPopupView.hidden = YES;
        NSURL* url = [NSURL URLWithString:self.LinkStr];
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        [self.mWebView loadRequest:request];
    }else if (sender.tag == 1){
        self.mPopupView.hidden = YES;
        if (_mWebView.canGoBack) {
            [_mWebView goBack];
        }
    }else if (sender.tag == 2){
        self.mPopupView.hidden = YES;
        if (_mWebView.canGoForward) {
            [_mWebView goForward];
        }
    }else if (sender.tag == 3){
        self.mPopupView.hidden = YES;
        [_mWebView reload];
    }else if (sender.tag == 4){
        if (self.mPopupView.hidden == YES) {
            self.mPopupView.hidden = NO;
        }else{
            self.mPopupView.hidden = YES;
        }
    }
}

//分享事件
- (void)OneBtnAction
{
    self.mPopupView.hidden = YES;
    [SVProgressHUD showWithStatus:@"加载中..."];
    [HTTPManagers getWithOpenURL:ShareAddress params:nil success:^(id json) {
        if (![json isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        if ([json[@"status"] integerValue] == 1 ) {
            NSDictionary *innerDic = json[@"msg"];
            if ([innerDic isKindOfClass:[NSDictionary class]]) {
                NSString *aOpen = [NSString stringWithFormat:@"%@",json[@"msg"][@"open"]];
                if ([aOpen isEqualToString:@"1"]) {
                    state = @"1";
                    self.mDictionary  = json[@"msg"];
                    [self PopShareView];
                }else if ([aOpen isEqualToString:@"0"]){
                    state = @"0";
                    [self PopShareView];
                }
                
            }
        }
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"请检查网络"];
    }];
}


    
 - (void)PopShareView
{
    NSString *textToShare; //分享的标题
    NSString *UrlStr;
    if ([state isEqualToString:@"0"]) {
        textToShare = @"";
        UrlStr = @"";
    }else if ([state isEqualToString:@"1"]){
        textToShare = self.mDictionary[@"links"];
        UrlStr = @"";//返回的links格式有问题要返回正确的urlStr格式 self.mDictionary[@"links"]
    }
    //分享的图片
//    UIImage *imageToShare = [UIImage imageNamed:@"lunbo1"];
    //分享的url
    NSURL *urlToShare = [NSURL URLWithString:UrlStr];
    
    //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    //不出现在活动项目
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };
    
}


//推送消息事件
- (void)TwoBtnAction
{
    self.mPopupView.hidden = YES;
    
    NSDictionary *aDic = [UserDefault objectForKey:UserDefalt_News];
    NSLog(@"webDic  =  %@",aDic);
    if (aDic !=nil) {
        [CustomAltView createAltViewWithTitle:@"最新消息" andMessage:aDic[@"aps"][@"alert"]];
    }else{
        [CustomAltView createAltViewWithTitle:@"暂无消息" andMessage:nil];
    }
    
    
    
    
}
- (void)ThrBtnAction
{
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    [SVProgressHUD showSuccessWithStatus:@"清除成功"];
    self.mPopupView.hidden = YES;
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self showWaitingProgress];
    
}



- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [self dissProgress:nil];

    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *url = navigationAction.request.URL.absoluteString;
    if (![navigationAction.request.URL.scheme isEqualToString:@"https"] &&
        ![navigationAction.request.URL.scheme isEqualToString:@"http"])
    {
        /************************************/
        /***** 下列也可不做判断。直接  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];*****/
        /***** 如果需要做如下的判断(手机是否有装微信或支付宝，qq钱包)，需要在info.plist文件内添加白名单 *****/
        /************************************/
        
        if ([url containsString:@"weixin"]) {
            if (![self checkoutIphoneHaveWeiXin]) {
                /***** 提示用户未安装微信 *****/
                
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            }
            
        } else if([url containsString:@"alipay"]) {
            
            if (![self checkoutIphoneHaveAlipay]) {
                /***** 提示用户未安装支付宝 *****/
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            }
            
        } else {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    
    
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


- (BOOL)checkoutIphoneHaveWeiXin {
    
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin:"]];
}


- (BOOL)checkoutIphoneHaveAlipay {
    
    
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay:"]];
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
}


- (void)dissProgress:(NSString*)message{
    if (message) {
        if ([message isEqualToString:@"NSURLErrorDomain"]) {
            [SVProgressHUD showErrorWithStatus:@"网络请求错误"];
        }else if([message isEqualToString:@"NSCocoaErrorDomain"]){
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }else{
            [SVProgressHUD showErrorWithStatus:message];
        }
    }else{
        [SVProgressHUD dismiss];
    }
}

- (void)showWaitingProgress{
    [SVProgressHUD showWithStatus:@"请等待"];
}


@end
